const WebSocket = require('ws');
const uuid = require('uuid');

// 存储在线用户信息
const onlineUsers = {};
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  // 为连接的用户生成唯一ID
  const userId = uuid.v4();
  ws.userId = userId;
  ws.username = null;

  ws.on('message', (message) => {
    const data = JSON.parse(message);
    if (data.type === 'login') {
      // 处理用户登录
      ws.username = data.username;
      onlineUsers[userId] = {
        socket: ws,
        username: data.username
      };
      const loginMessage = {
        type: 'loginSuccess',
        message: '登录成功',
        userId: userId,
        username: data.username
      };
      ws.send(JSON.stringify(loginMessage));
    } else if (data.type ==='message') {
      // 处理消息发送
      const { toUserId, content } = data;
      const targetUser = onlineUsers[toUserId];
      if (targetUser) {
        const messageData = {
          type:'message',
          fromUserId: ws.userId,
          fromUsername: ws.username,
          content: content
        };
        targetUser.socket.send(JSON.stringify(messageData));
      } else {
        const errorMessage = {
          type: 'error',
          message: '目标用户不存在'
        };
        ws.send(JSON.stringify(errorMessage));
      }
    }
  });

  ws.on('close', () => {
    if (ws.username) {
      // 用户断开连接时，从在线用户列表移除
      delete onlineUsers[ws.userId];
    }
    console.log('Connection closed');
  });
});